package mysql

/**
 * @Title  mysql操作层
 * @Description mysql操作的封装
 * @Author yaoweixin
 * @Update 2020/11/20 10:08
 */

import (
	"gitee.com/yaodae/server-lib-go/config"
	"gitee.com/yaodae/server-lib-go/log"
)

func Init(cfg *config.MysqlConfig) bool {
	if cfg == nil {
		return true
	}
	list := make([]MServerConfig, 0)
	for _, dbCfg := range cfg.MysqlDb {
		mysqlSConfig := MServerConfig{Name: dbCfg.MysqlName, User: dbCfg.MysqlUser, Password: dbCfg.MysqlPwd, Db: dbCfg.MysqlDb, Url: dbCfg.MysqlUrl}
		list = append(list, mysqlSConfig)
	}
	mysqlConfig := MConfig{MaxIdle: cfg.MysqlMaxIdle, MaxActive: cfg.MysqlMaxActive, Configs: list}
	initMysql(mysqlConfig)
	return true
}

type Query struct {
	Key   string
	value string
}

func GetDb() string {
	return "default"
}

// MFindOne 查找一个数据
func MFindOne(dest interface{}) int64 {
	return getConn(GetDb()).Where(dest).First(dest).RowsAffected
}

// MFindList 查找数据列表
func MFindList(dest interface{}, destList interface{}) int64 {
	return getConn(GetDb()).Where(dest).Model(dest).Find(destList).RowsAffected
}

// MFindListByIn 根据in查询查找数据列表
func MFindListByIn(sql string, destList interface{}) int64 {
	return getConn(GetDb()).Raw(sql).Find(destList).RowsAffected
}

// MAdd 插入数据
func MAdd(dest interface{}) int64 {
	result := getConn(GetDb()).Create(dest)
	if result.Error != nil {
		log.Error("mysql add error================", result.Error)
		return 0
	} else {
		return result.RowsAffected
	}
}

// MSave 更新数据
func MSave(dest interface{}) int64 {
	result := getConn(GetDb()).Save(dest)
	if result.Error != nil {
		log.Error("mysql save error================", result.Error)
		return 0
	} else {
		return result.RowsAffected
	}
}

// MRemove 删除数据
func MRemove(dest interface{}) int64 {
	result := getConn(GetDb()).Delete(dest)
	if result.Error != nil {
		log.Error("mysql save error================", result.Error)
		return 0
	} else {
		return result.RowsAffected
	}
}

// MExec 执行SQL
func MExec(sql string, values ...interface{}) int64 {
	result := getConn(GetDb()).Exec(sql, values...)
	if result.Error != nil {
		log.Error("mysql exec error================", result.Error)
		return 0
	} else {
		return result.RowsAffected
	}
}
